// stores/useMenuStore.ts
import { defineStore } from 'pinia'

export interface Menu {
  id: number
  label: string,
  route: string,
}

export interface Tab {
  id: number
  label: string,
  route: string,
}

export const useMenuStore = defineStore('menus', {
  state: () => ({
    menuList: [
      { id: 1, label: 'Tab 1', route: 'Page1' },
      { id: 2, label: 'Tab 2', route: 'Page2' },
      { id: 3, label: 'Tab 3', route: 'Page3' },
      { id: 4, label: 'Tab 4', route: 'Page4' },
      { id: 5, label: 'Tab 5', route: 'Page5' },
      { id: 6, label: 'Tab 6', route: 'Page6' },
    ] as Menu[],
    tabsList: [] as Tab[],
    activeMenuId: -1,
    windowId: 0,
  }),

  actions: {
    /**
     * 点击左侧菜单
     */
    handleMenuClick(menuId: number) {
      this.activeMenuId = menuId

      const exists = this.tabsList.find(tab => tab.id === menuId)
      if (!exists) {
        const menu = this.menuList.find(m => m.id === menuId)
        if (menu) {
          this.tabsList.push({ ...menu })
        }
      }
    },

    /**
     * 点击切换 Tab
     */
    handleTabClick(tabId: number) {
      console.log('切换了一个激活的tab')

      this.activeMenuId = tabId
    },

    /**
     * 删除 Tab
     */
    closeTab(tabId: number) {
      if (this.tabsList.length <= 1) return // 最少保留一个 tab

      const index = this.tabsList.findIndex(tab => tab.id === tabId)
      if (index === -1) return

      // 删除前判断是否是激活的 tab
      if (this.activeMenuId === tabId) {
        console.log('删除了一个激活的tab')
        // 先尝试选中前一个 tab
        if (index > 0) {
          this.activeMenuId = this.tabsList[index - 1].id
        } else if (index < this.tabsList.length - 1) {
          this.activeMenuId = this.tabsList[index + 1].id
        }
        console.log(this.activeMenuId)
      }

      this.tabsList.splice(index, 1)
    },
  },
})
